using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using SteveTPham.QueryAnything.DataSetTools;

namespace UnitTests
{
	class Program
	{
		private static DataSet testData;
		private static QueryManager qm;

		static void Main(string[] args)
		{
			InitTestData();

			RunTests();
		}

		private static void RunTests()
		{
			RunSelect();
			RunInsert();
			RunUpdate();
			RunDelete();
		}

		#region Expects methods
		private static void Expects(QueryResult r, bool expected, string message)
		{
			if (expected)
				return;

			Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, message, r.ErrorText, r.TextResult);
			throw new ApplicationException("unexpected: " + message);
		}

		private static void ExpectsColumns(QueryResult r, params string[] columns)
		{
			DataTable dt = r.DataResult;
			if (dt == null)
				throw new ApplicationException("DataResult is null");


			if (columns.Length != dt.Columns.Count)
				throw new ApplicationException("incorrect number of columns");

			for (int i = 0; i < dt.Columns.Count; i++)
			{
				string c = dt.Columns[i].ColumnName;

				if (!c.Equals(columns[i], StringComparison.OrdinalIgnoreCase))
					throw new ApplicationException("Expected '" + columns[i] + "'; but found '" + c + "'");
			}
		}

		private static QueryResult Run(string query)
		{
			Console.WriteLine("Running: " + query);
			QueryResult r = qm.Run(query);

			if (!string.IsNullOrEmpty(r.ErrorText))
				throw new ApplicationException(r.ErrorText);

			return r;
		}
		#endregion
		#region DML Tests
		private static void RunSelect()
		{
			QueryResult r;

			r = Run("select * from customers");
			Expects(r, r.RowAffected == 91, "select customer");
			ExpectsColumns(r, "CustomerID", "CompanyName", "ContactName", "ContactTitle", "Address", "City", "Region", "PostalCode", "Country", "Phone", "Fax");


			//throw new Exception("The method or operation is not implemented.");
		}

		private static void RunInsert()
		{
			//throw new Exception("The method or operation is not implemented.");
		}

		private static void RunUpdate()
		{
			//throw new Exception("The method or operation is not implemented.");
		}

		private static void RunDelete()
		{
			//throw new Exception("The method or operation is not implemented.");
		}
		#endregion

		private static void InitTestData()
		{
			if (testData != null)
				return;

			Console.Write("Initializing test data... ");
			testData = new DataSet();
			testData.ReadXml(@"..\..\..\__ SampleFiles\nwind-UnitTest.xml");

			qm = new QueryManager(testData);

			Console.WriteLine("done.");
		}
	}
}
